<template>
  <div class="container">
    <!-- 固定头部区域 -->
    <div class="header-section">
      <!-- 导航栏 -->
      <div class="tab-bar">
        <div :class="['tab-item', { active: activeTab === 'product' }]" @click="setActiveTab('product')">
          <div class="tab-icon-wrapper">
            <img v-if="hasImage('proinfo')" :src="getImageUrl('proinfo')" alt="产品信息" class="tab-icon" />
            <div v-else class="tab-icon-placeholder"></div>
          </div>
          <span>产品信息</span>
        </div>
        <div :class="['tab-item', { active: activeTab === 'circulation' }]" @click="setActiveTab('circulation')">
          <div class="tab-icon-wrapper">
            <img v-if="hasImage('logisticsinfo')" :src="getImageUrl('logisticsinfo')" alt="产品凭证" class="tab-icon" />
            <div v-else class="tab-icon-placeholder"></div>
          </div>
          <span>产品凭证</span>
        </div>
        <div :class="['tab-item', { active: activeTab === 'anti-counterfeit' }]" @click="setActiveTab('anti-counterfeit')">
          <div class="tab-icon-wrapper">
            <img v-if="hasImage('fangwei')" :src="getImageUrl('fangwei')" alt="防伪信息" class="tab-icon" />
            <div v-else class="tab-icon-placeholder"></div>
          </div>
          <span>防伪信息</span>
        </div>
      </div>
    </div>

    <!-- 白底主内容区域 -->
    <div class="main-wrapper">
      <div v-if="!loading" class="main-content">

        <!-- 产品信息 tab -->
        <div v-show="activeTab === 'product'" class="tab-content">
          <div class="product-header-container">
            <!-- 产品图片头图 -->
            <div class="product-image-header">
              <img v-if="product.productImageUrl" :src="product.productImageUrl" alt="产品头图" class="header-product-image" />
              <div v-else class="product-image-placeholder">暂无图片</div>
            </div>
            <div class="product-info">
              <div class="image-and-caption">
                <p>图片仅供参考，请以实物为准</p>
              </div>
              <div class="row-title-circle">
                <span class="cpxx">产品信息</span>
              </div>
            </div>
          </div>

          <!-- 属性列表 -->
          <ul class="list">
            <li><h5>产品名称</h5><p>{{ product.productName }}</p></li>
            <!-- <li><h5>二维码编号</h5><p>{{ product.qrCodeId }}</p></li> -->
            <!-- <li><h5>产品编码</h5><p>{{ product.code }}</p></li> -->
            <li><h5>属性</h5><p class="pei-liao">{{ product.attributes }}</p></li>
            <li><h5>规格</h5><p>{{ product.specification }}</p></li>
            <li><h5>单位</h5><p>{{ product.unit }}</p></li>
            <li><h5>厂家地址</h5><p class="pei-liao">{{ product.manufacturer }}</p></li>
            <li><h5>批次号</h5><p>{{ product.batchNumber }}</p></li>
            <!-- <li><h5>说明</h5><p>{{ product.description }}</p></li> -->
          </ul>
        </div>

        <!-- 产品凭证 tab -->
        <div v-show="activeTab === 'circulation'" class="tab-content">
          <ul class="list">
            <li>
              <h5>产品凭证</h5>
              <div class="product-credential-images">
                <div v-for="(url, index) in product.imageUrlList" :key="index" class="credential-image-item">
                  <img :src="url" alt="产品凭证图片" v-if="url" />
                  <div class="image-placeholder" v-else>无图片</div>
                </div>
                <p v-if="!product.imageUrlList || product.imageUrlList.length === 0">暂无凭证图片</p>
              </div>
            </li>
          </ul>
        </div>

        <!-- 防伪信息 tab -->
        <div v-show="activeTab === 'anti-counterfeit'" class="tab-content">
          <p>暂无防伪信息</p>
        </div>
      </div>

      <div v-else class="loading">加载中...</div>
    </div>
  </div>
</template>


<script>
import { getQrDetail } from '@/api/mes/qr/scan'

// 尝试导入图片，如果不存在则设置为null
let proinfoImage, logisticsinfoImage, fangweiImage;

try {
  proinfoImage = require('@/assets/images/proinfo.png');
} catch (e) {
  proinfoImage = null;
}

try {
  logisticsinfoImage = require('@/assets/images/logisticsinfo.png');
} catch (e) {
  logisticsinfoImage = null;
}

try {
  fangweiImage = require('@/assets/images/fangwei.png');
} catch (e) {
  fangweiImage = null;
}

export default {
  name: 'TraceabilityDetail',
  data() {
    return {
      loading: true,
      activeTab: 'product',
      product: {
        productName: '',
        qrCodeId: '',
        code: '',
        imageUrlList: [],
        attributes: '',
        specification: '',
        unit: '',
        manufacturer: '',
        batchNumber: '',
        description: '',
        productImageUrl: '',
      },
      // 图片资源映射
      imageResources: {
        proinfo: proinfoImage,
        logisticsinfo: logisticsinfoImage,
        fangwei: fangweiImage
      }
    }
  },
  created() {
    document.title = "觅康溯源平台"
    this.getDetail()
  },
  methods: {
    setActiveTab(tab) {
      this.activeTab = tab
    },
    // 获取图片URL
    getImageUrl(imageName) {
      return this.imageResources[imageName] || ''
    },
    // 检查图片是否存在
    hasImage(imageName) {
      return !!this.imageResources[imageName]
    },
    // 处理图片路径
    processImageUrl(url) {
      if (!url) return '';

      // 如果已经是完整URL，直接返回
      if (url.startsWith('http')) {
        return url;
      }

      // 处理相对路径
      let processedUrl = url;

      // 去除 /dev-api 前缀（如果存在）
      if (processedUrl.startsWith('/dev-api/')) {
        processedUrl = processedUrl.substring(9); // 去掉 '/dev-api' 部分
      }

      // 确保路径以 '/' 开头
      if (!processedUrl.startsWith('/')) {
        processedUrl = '/' + processedUrl;
      }

      // 拼接完整URL
      return `http://${window.location.hostname}:18081${processedUrl}`;
    },
    getDetail() {
      let url = window.location.href;
      let params = url.split('?')[1];
      let paramsObj = {};
      if (params) {
        let paramsArr = params.split('&');
        for (let i = 0; i < paramsArr.length; i++) {
          let param = paramsArr[i].split('=');
          paramsObj[param[0]] = param[1];
        }
      }

      const qrCodeId = paramsObj['qrCodeId'];

      // 参数校验
      if (!qrCodeId) {
        console.error('缺少二维码参数');
        this.loading = false;
        return;
      }

      getQrDetail(qrCodeId).then(response => {
        console.log("获取成功：", response)
        const data = response.data || {}

        // 处理产品主图路径
        let productImageUrl = this.processImageUrl(data.productImageUrl);

        // 处理凭证图片路径
        let imageUrlList = [];
        if (data.imageUrl) {
          const urls = data.imageUrl.split(',');
          imageUrlList = urls.map(url => this.processImageUrl(url));
        }

        this.product.productName = data.productName || '未知'
        this.product.qrCodeId = data.qrCodeId || '未知'
        this.product.code = data.code || '未知'
        this.product.imageUrlList = imageUrlList
        this.product.attributes = data.attributes || '未知'
        this.product.specification = data.specification || '未知'
        this.product.unit = data.unit || '未知'
        this.product.manufacturer = data.manufacturer || '未知'
        this.product.batchNumber = data.batchNumber || '未知'
        this.product.description = data.description || '未知'
        this.product.productImageUrl = productImageUrl

        this.loading = false
      }).catch(error => {
        console.error('请求失败:', error)
        // 使用更安全的错误提示方式
        if (this.$message) {
          this.$message.error('数据加载失败')
        }
        this.loading = false
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 0 20px 20px;
  background-image: url('~@/assets/images/login-background.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 100vh;
  position: relative;
}

.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 0;
}

/* 固定头部 */
.header-section {
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo-container {
  display: flex;
  align-items: center;
  padding: 10px 0;
  box-sizing: border-box;
  z-index: 3;
  position: relative;
  background-color: rgba(255, 255, 255, 0.9);
}

.banner-logo {
  width: 20vw;
  height: auto;
  margin-right: 20px;
}

.banner-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
}

.tab-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 0;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eee;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.tab-item {
  text-align: center;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  padding: 6px 12px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.tab-item.active {
  color: #fff;
  background-color: #1d6ca7;
  border-radius: 6px;
}

.tab-icon-wrapper {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.tab-icon {
  width: 24px;
  height: 24px;
}

.tab-icon-placeholder {
  width: 24px;
  height: 24px;
  background-color: #f0f0f0;
  border-radius: 50%;
}

/* 白底主内容 */
.main-wrapper {
  position: relative;
  z-index: 2;
  background-color: #fff;
  margin-top: 10px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-header-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 15px;
}

.product-image-header {
  width: 100px;
  height: 100px;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.header-product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-image-placeholder,
.image-placeholder {
  color: #999;
  font-size: 12px;
  text-align: center;
}

.product-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.image-and-caption {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 5px;
  font-size: 10px;
  color: #999;
}

.row-title-circle {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: bold;
  color: #1d6ca7;
}

.list {
  list-style: none;
  padding-left: 0;
}

.list li {
  padding: 10px 0;
  border-bottom: 1px solid #ddd;
}

.list h5 {
  font-size: 14px;
  margin: 0;
  color: #333;
}

.list p {
  margin: 5px 0;
  color: rgba(51, 51, 51, 0.6);
  line-height: 24px;
}

.pei-liao {
  word-break: break-all;
}

.loading {
  text-align: center;
  padding: 40px;
  font-size: 16px;
}

.product-credential-images {
  display: flex;
  flex-direction: column; /* 改为垂直排列 */
  gap: 10px;
}

.credential-image-item {
  width: 100%; /* 宽度占满容器 */
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  aspect-ratio: 1; /* 保持宽高比 */
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.credential-image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 移动端适配：屏幕较小时每行显示 2 张图片 */
/* @media (max-width: 600px) {
  .credential-image-item {
    width: calc(50% - 5px);
  }

  .product-header-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .product-image-header {
    width: 100%;
    max-width: 150px;
  }
} */
</style>
